package com.princess.demok.view.bessel;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.princess.baselib.utils.LogUtils;

public class KeySineView extends View {

    float progress = 0;
    Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public KeySineView(Context context) {
        super(context);
    }

    public KeySineView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public KeySineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    {
        mPaint.setTextSize(dpToPixel(40));
        mPaint.setTextAlign(Paint.Align.CENTER);
    }

    public float getProgress() {
        return progress;
    }

    public void setProgress(float progress) {
        this.progress = progress;
        invalidate();
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setColor(Color.parseColor("#E91E63"));
        mPaint.setStyle(Paint.Style.STROKE);

        mPaint.setStrokeWidth(dpToPixel(4));

        // 振幅
        int amplitude = 150;

        int height = getHeight();
        // 波长
        int width = getWidth();
        int index = 1;

        Path mPath = new Path();
        mPath.reset();
        while (index <= progress / 100 * width) {
            float endY = (float) (Math.sin((float) index / (float) width * 2f * Math.PI)
                    * (float) amplitude + height - amplitude);
            if (index==1){
                mPath.moveTo(index, endY-dpToPixel(4));
            }
            mPath.lineTo(index, endY-dpToPixel(4));
            Log.i("sine", index + "  " + endY);
            index++;
        }

        canvas.drawPath(mPath, mPaint);
    }

    public float dpToPixel(float dp) {
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        return dp * metrics.density;
    }
}
